package sms

import (
	"encoding/json"

	"admin.supervise.limaochuxing.top/admin/schemas/resp"
	"admin.supervise.limaochuxing.top/core/response"
	"admin.supervise.limaochuxing.top/model/system"
	"admin.supervise.limaochuxing.top/util/sms"

	"time"

	"admin.supervise.limaochuxing.top/util"

	"fmt"

	"gorm.io/gorm"
)

type ISmsService interface {
	SendLoginCode(mobile string) (*resp.SmsSendLoginCodeResp,error)
}

type smsService struct {
	db *gorm.DB
}

func NewSmsService(db *gorm.DB) ISmsService {
	return &smsService{db: db}
}

func (s *smsService) SendLoginCode(mobile string) (*resp.SmsSendLoginCodeResp,error) {
    // Redis键定义
    codeKey := fmt.Sprintf("sms_code:%s", mobile)
    lockKey := fmt.Sprintf("sms_lock:%s", mobile)

    // 1分钟锁定检查
	fmt.Println("lockKey",lockKey)
    if exist:= util.RedisUtil.Exists(lockKey); exist>0 {
		fmt.Println("lockKey",exist)
        return &resp.SmsSendLoginCodeResp{Ret: false}, response.Failed.Make("操作过于频繁，请稍后再试")
    }

	code:=util.ToolsUtil.GenerateSmsCode(4)
	manager:=sms.NewSmsManager()
	smsResp,err := manager.SendLoginCode(mobile, code)
	content:=map[string]string{
		"code":code,
	}
	contentBytes, _ := json.Marshal(content)
	var result string
	if err!=nil{
		result=err.Error()
	}else{
		result=smsResp.Data
		// 发送短信成功后设置锁定
		util.RedisUtil.Set(lockKey, "1", 60)
		util.RedisUtil.Set(codeKey, code, 300)
	}
	go func ()  {
		// 记录发送日志
		log := system.SystemLogSms{
			Scene:1,
			Mobile:   mobile,
			Content: string(contentBytes),
			Status:   map[bool]int8{true: 1, false: 0}[err == nil],
			Results: result ,
			SendTime: time.Now().Unix(),
		}
		s.db.Create(&log)
	}()	
	return &resp.SmsSendLoginCodeResp{
		Ret: err==nil,
	},nil
}